//
//  Date.swift
//  
//
//  Created by tangbl93 on 2021/1/6.
//

import Foundation

// MARK: Property
public extension Date {
    
    /// unix time
    var yx_unix: TimeInterval {
        return timeIntervalSince1970
    }
    
    // current unix time
    static var yx_currentUnix: TimeInterval {
        return Date().yx_unix
    }
    
    // the start of current date
    var yx_startOfDay: Date {
        return Calendar.current.startOfDay(for: self)
    }
}

// MARK: Compare
public extension Date {
    
    // startDay of this week -> Monday(星期一)
    static func yx_startDayOfThisWeek(_ date: Date = Date()) -> Date {
        var calendar = Calendar.current
        // https://bit.ly/3r041G4
        calendar.firstWeekday = 2
        
        let components = calendar.dateComponents(
            Set<Calendar.Component>([.yearForWeekOfYear, .weekOfYear]), from: date)
        
        let startDayOfThisWeek = calendar.date(from: components)
        return startDayOfThisWeek ?? date
    }
    
    // startDay of this month
    static  func yx_startDayOfThisMonth(_ date: Date = Date()) -> Date {
        let calendar = NSCalendar.current
        let components = calendar.dateComponents(
            Set<Calendar.Component>([.year, .month]), from: date)
        
        let startDayOfThisMonth = calendar.date(from: components)
        
        return startDayOfThisMonth ?? date
    }
}

// MARK: Convert
public extension Date {
    
    /// convert to string with format
    func yx_string(with format:String, dateFormatter: DateFormatter = DateFormatter.yx_current) -> String {
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}
